package com.mz.mattress.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mz.mattress.admin.api.req.MemberQueryReq;
import com.mz.mattress.admin.api.resp.MemberCount;
import com.mz.mattress.admin.mapper.MemberMapper;
import com.mz.mattress.admin.mapper.OrderMapper;
import com.mz.mattress.admin.service.MemberService;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.entity.Member;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Result<IPage<Member>> listPage(MemberQueryReq req) {
        Page page = req.newPage();
        Page<Member> list = memberMapper.listPage(page, req.getMobile(), req.getStatus(), req.getStartTime(), req.getEndTime());
        return Result.ok(list);
    }

    @Override
    public Result<Member> getById(Long id) {
        Member member = memberMapper.selectById(id);
        return Result.ok(member);

    }

    @Override
    public Result add(Member member) {

        if (StringUtils.isEmpty(member.getMobile())) {
            return Result.fail("请输入手机号");
        }

        if (StringUtils.isEmpty(member.getName())) {
            return Result.fail("请输入姓名");
        }

        String mobile = member.getMobile();

        Member one = memberMapper.selectByMobile(mobile);
        if (one != null) {
            return Result.fail("手机号已存在");
        }

        memberMapper.insert(member);

        return Result.ok();
    }

    @Override
    public Result updateById(Member member) {

        // 手机号不能改
        member.setMobile(null);

        memberMapper.updateById(member);

        return Result.ok();
    }

    @Override
    public Result deleteByIds(Set<Long> ids) {
        memberMapper.deleteBatchIds(ids);
        return Result.ok();
    }

    @Override
    public void calMemberOrderCount() {

        List<MemberCount> list = orderMapper.sumMemberOrderCount();

    }


}
